class EntriesController < ApplicationController

  def index
    if @runner
      return self.unauthorized unless self.current_user.can('view:entries', @runner)
      @entries = @runner.entries  
    else
      # i don't think this will ever be a case, or shouldn't be - nick
      # i can't really put a permission on viewing all the entries
      @entries = Entry.find(:all)
    end
  end

  def show
    @entry = Entry.find(params[:id])
    return self.unauthorized unless self.current_user.can('view:entries', @entry.runner)
    add_page_token(@entry.info)
  end

  def new
    if params[:runner_id]
      @runner = Runner.find(params[:runner_id])
      @lap = @runner.group.lap
    end
    return self.unauthorized unless @runner
    return self.unauthorized unless self.current_user.can('create:entries', @runner)
    @entry = Entry.new
  end

  def edit
    @entry = Entry.find(params[:id])
    @runner = @entry.runner
    @lap = @runner.group.lap
    return self.unauthorized unless self.current_user.can('edit:entries', @entry.runner)
    
    add_page_token(@entry.info)
  end

  def create
    if params[:entry]['runner_id']
      @lap = Runner.find(params[:entry]['runner_id']).group.lap
    end
    @entry = Entry.new(params[:entry])
    return self.unauthorized unless self.current_user.can('edit:entries', @entry.runner)

    if @entry.save
      flash[:notice] = 'Entry was successfully created.'
      redirect_to(@entry)
    else
      render :action => "new", :runner_id => params[:entry]['runner_id']
    end
  end

  def update
    @entry = Entry.find(params[:id])
    add_page_token(@entry.info)
    @runner = @entry.runner
    @lap = @runner.group.lap

    return self.unauthorized unless self.current_user.can('edit:entries', @entry.runner)

    if @entry.update_attributes(params[:entry])
      flash[:notice] = 'Entry was successfully updated.'
      redirect_to(@entry)
    else
      render :action => "edit"
    end
  end

  def destroy
    @entry = Entry.find(params[:id])
    @runner = @entry.runner
    return self.unauthorized unless self.current_user.can('delete:entries', @entry.runner)
    @entry.destroy

    redirect_to @runner
  end

end
